<template>
  <s-layout title="全部成员" :bgStyle="{ backgroundColor: '#f5f7fa' }">

    <!-- User List Container -->
    <view class="user-list-container">
      <view class="user-card" v-for="(item, index) in peopleList" :key="item.cu_id || index">
        <!-- Left: Avatar -->
        <view class="user-avatar">
          <image class="avatar-img" :src="item.cu_avatarUrl" mode="aspectFill" alt="User Avatar"></image>
        </view>

        <!-- Center: Info -->
        <view class="user-info">
          <view class="user-header">
            <text class="user-name">{{ item.cu_name }}</text>
            <view class="job-tag" v-if="item.cu_job">{{ item.cu_job }}</view>
          </view>

          <view class="user-contact">
            <view class="info-row">
              <uni-icons type="phone-filled" size="16" color="#1989FA"></uni-icons>
              <text class="user-detail">{{ item.cu_phone || '暂无' }}</text>
            </view>
            <view class="info-row">
              <uni-icons type="person-filled" size="16" color="#1989FA"></uni-icons>
              <text class="user-detail">{{ item.wx_user || 'N/A' }}</text>
            </view>
          </view>


        </view>

        <!-- Right: Actions (Edit/Delete) -->
        <view class="action-buttons">
          <view class="action-icon edit-icon" @click="navigateToUpdate(item)">
            <uni-icons type="compose" size="18" :color="themeColor"></uni-icons>
          </view>
          <view class="action-icon delete-icon" @click="handleDeleteConfirmation(item)">
            <uni-icons type="trash" size="18" color="#e43d33"></uni-icons>
          </view>
        </view>
      </view>

      <!-- Placeholder if list is empty -->
      <s-empty v-if="!isLoading && peopleList.length === 0" text="暂无成员" icon="people-empty" marginTop="100rpx"></s-empty>
       <!-- Loading State -->
      <view v-if="isLoading" class="loading-container">
        <uni-load-more status="loading"></uni-load-more>
      </view>
    </view>


    <fui-button
      @click="handleAddMember"
      radius="96rpx"
      btnSize="medium"
      style="
        position: fixed;
        bottom: 50rpx;
        left: 50%;
        transform: translateX(-50%);
        padding: 8px 16px;
        border: none;
        font-size: 30rpx;
      "
      ><text
        class="cicon-add-round-o"
        style="font-size: 40rpx; margin-right: 20rpx"
      ></text>
      <p>添加</p>
    </fui-button>
  </s-layout>
</template>

<script setup lang="ts">
import sheep from '@/sheep';
import { onLoad } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
import other from '@/sheep/api/other';
// Define theme color for reuse
const themeColor = ref('#007aff'); // Your primary blue

interface PeopleListItem {
  company_id: string;
  createtime?: string;
  cu_avatarUrl: string;
  cu_email: string;
  cu_id: string;
  cu_job: string;
  cu_name: string;
  cu_phone: string;
  cu_role?: string;
  cu_status?: string;
  del_type?: string;
  updatetime?: string;
  user_id?: string;
  wx_id?: string;
  wx_pawd: string;
  wx_user: string;
  passwordVisible?: boolean; // UI state
}

const companyId = ref<string | null>(null);
const isLoading = ref(false); // Loading state
const peopleList = reactive<Array<PeopleListItem>>([]);

// --- Navigation & Actions ---
const goBack = () => {
  sheep.$router.back();
};

const handleAddMember = () => {
  if (!companyId.value) {
     uni.showToast({ title: '缺少公司信息', icon: 'none' });
     return;
  }
  // Example navigation, adjust path/params as needed
  // Note: The example path '/pages/qy/hiddendanger/update' seems unrelated to adding members.
  // Using the previous correct path.
  uni.navigateTo({
     url: `/pages/other/peopleList/update?companyId=${companyId.value}`,
  });
};

const navigateToUpdate = (item: PeopleListItem) => {
  if (!companyId.value) {
     uni.showToast({ title: '缺少公司信息', icon: 'none' });
     return;
  }
  // 将完整的用户数据转换为 JSON 字符串
  const userData = encodeURIComponent(JSON.stringify({
    company_id: item.company_id,
    createtime: item.createtime,
    cu_avatarUrl: item.cu_avatarUrl,
    cu_email: item.cu_email,
    cu_id: item.cu_id,
    cu_job: item.cu_job,
    cu_name: item.cu_name,
    cu_phone: item.cu_phone,
    cu_role: item.cu_role,
    cu_status: item.cu_status,
    del_type: item.del_type,
    updatetime: item.updatetime,
    user_id: item.user_id,
    wx_id: item.wx_id,
    wx_pawd: item.wx_pawd,
    wx_user: item.wx_user
  }));
  uni.navigateTo({
    url: `/pages/other/peopleList/update?companyId=${companyId.value}&userData=${userData}`,
  });
};

// --- Password Visibility ---
const togglePasswordVisibility = (item: PeopleListItem) => {
  item.passwordVisible = !item.passwordVisible;
};

// --- Delete Logic ---
const handleDeleteConfirmation = (item: PeopleListItem) => {
   if (!item.cu_id) {
       uni.showToast({ title: '无法删除该成员', icon: 'none' });
       return;
   }
   uni.showModal({
       title: '确认删除',
       content: `确定要删除成员 ${item.cu_name} 吗？`,
       success: (res) => {
           if (res.confirm) {
               console.log('用户点击确定');
               peopleListDelete(item);
           } else if (res.cancel) {
               console.log('用户点击取消');
           }
       }
   });
};

const peopleListDelete = async (item: PeopleListItem) => {
  if (!item.cu_id) return;
  isLoading.value = true;
  console.log('peopleListDelete', item);
  try {
    const params = {
      tpu_id: item.cu_id,
      wx_id: item.wx_id,
    };
    await other.deleteThirdPartyCompanyUser(params);
    console.log("peopleListDelete successful for ID:", item.cu_id);
    uni.showToast({ title: '删除成功', icon: 'success' });
    const index = peopleList.findIndex(p => p.cu_id === item.cu_id);
    if (index > -1) {
      peopleList.splice(index, 1);
    }
  } catch (error) {
    console.error("peopleListDelete failed:", error);
    uni.showToast({ title: '删除失败', icon: 'error' });
  } finally {
    isLoading.value = false;
  }
};

// --- API Interaction ---
const peopleListDetail = async (cId: string) => {
  isLoading.value = true;
  peopleList.splice(0, peopleList.length); // Clear list before fetching
  const params = { third_company_id: cId };
  try {
    const res = await other.getThirdPartyCompanyInfo(params);
    console.log("peopleListInfo response:", res);
    // 打印详细的用户信息以便诊断
    if (res.code == 200 && Array.isArray(res.third_company_user_list) && res.third_company_user_list.length > 0) {
      console.log("第一个用户详情:", JSON.stringify(res.third_company_user_list[0]));
    }
    if (res.code == 200 && Array.isArray(res.third_company_user_list)) {
      // 处理返回的用户列表
      res.third_company_user_list.forEach(user => {
        console.log('处理用户数据:', user);
        // 根据接口实际返回字段创建用户对象
        const userItem: PeopleListItem = {
          company_id: user.company_id || '',
          createtime: user.createtime,
          cu_id: user.tpu_id,
          cu_name: user.tpu_name,
          cu_phone: user.tpu_phone,
          // 确保使用API返回的正确字段名称
          cu_avatarUrl: user.tpu_avatarUrl || '', 
          cu_job: user.tpu_job,
          cu_email: user.tpu_email,
          cu_role: user.tpu_role,
          cu_status: user.tpu_status,
          del_type: user.del_type,
          updatetime: user.updatetime,
          user_id: user.user_id,
          wx_id: user.wx_id,
          wx_pawd: user.wx_pawd || '',
          wx_user: user.wx_user || ''
        };
        console.log('映射后的用户数据:', userItem);
        // 额外检查，如果avatarUrl字段为空，使用备选值
        if (!userItem.cu_avatarUrl) {
          console.warn('Avatar URL missing for user:', user.tpu_name);
          userItem.cu_avatarUrl = 'https://assess.yuejin-tech.com/upload/avatarUrl/default.jpg'; // 默认头像
        }
        peopleList.push(userItem);
      });
    } else {
      console.warn("Failed to fetch or empty list:", res.msg || 'No data');
    }
  } catch (error) {
    console.error("peopleListDetail failed:", error);
    uni.showToast({ title: '加载成员列表失败', icon: 'none' });
  } finally {
    isLoading.value = false;
  }
  console.warn("peopleList", peopleList);
};

// --- Lifecycle ---
onLoad((options) => {
  if (options && options.companyId) {
    companyId.value = options.companyId;
    console.log("Company ID received:", companyId.value);
    peopleListDetail(companyId.value); // Fetch data on load
  } else {
    console.error("Company ID not found in options!");
    uni.showToast({ title: '缺少公司信息', icon: 'error', duration: 2000 });
     // Optionally disable add button or navigate back
  }
});
</script>

<style lang="scss" scoped>
// Use SCSS variables for consistency
$theme-color: #007aff;
$page-bg: #f5f7fa;
$card-bg: #ffffff;
$text-primary: #333333;
$text-secondary: #666666;
$text-placeholder: #999999;
$border-color: #e5e5e5;
$shadow-color: rgba(0, 0, 0, 0.06);
$delete-color: #e43d33;
$tag-bg: #e1f3fd;
$tag-color: #1989fa;

.user-list-container {
  padding: 24rpx;
  // Adjust bottom padding to be more than the button's height + desired space
  padding-bottom: calc(96rpx + 40rpx + 24rpx); // button height + bottom offset + extra space
}

.user-card {
  display: flex;
  align-items: flex-start;
  background-color: $card-bg;
  border-radius: 16rpx;
  padding: 30rpx 25rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx $shadow-color;
  transition: transform 0.2s, box-shadow 0.2s;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx $shadow-color;
  }
}

.user-avatar {
  width: 120rpx;
  height: 120rpx;
  margin-right: 25rpx;
  flex-shrink: 0;

  .avatar-img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: #eee;
    border: 3rpx solid rgba($theme-color, 0.2);
  }
}

.user-info {
  flex: 1;
  min-width: 0; // Important for flex children text overflow
  margin-right: 15rpx; // Space before action buttons
}

.user-header {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
  flex-wrap: wrap;
}

.user-name {
  font-size: 34rpx;
  font-weight: 600;
  color: $text-primary;
  margin-right: 12rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.job-tag {
  font-size: 22rpx;
  background-color: $tag-bg;
  color: $tag-color;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  font-weight: 500;
  display: inline-block;
  max-width: 200rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.user-contact {
  margin-bottom: 12rpx;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;

  .uni-icons {
    margin-right: 8rpx;
    flex-shrink: 0;
  }
}

.user-detail {
  font-size: 28rpx;
  color: $text-secondary;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

  &.password-label {
    display: inline;
    margin-right: 8rpx;
    margin-left: 6rpx;
  }
}

.user-password-row {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: $text-secondary;
}

.password-text {
  flex: 1;
  min-width: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.password-toggle-icon {
  padding: 5rpx;
  margin-left: 10rpx;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  flex-shrink: 0;
  height: 100%;
}

.action-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: rgba($theme-color, 0.05);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;

  &:active {
    background-color: rgba($theme-color, 0.1);
  }

  &.delete-icon {
    margin-top: 15rpx;
    background-color: rgba($delete-color, 0.05);

    &:active {
      background-color: rgba($delete-color, 0.1);
    }
  }
}

// Loading indicator style
.loading-container {
  padding: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
